#include "browsefolder.h"
#include "client.h"
#include "linkedlist.h"

BrowseFolder::BrowseFolder(QWidget *parent)
    : QDialog(parent)
{
	ui.setupUi(this);
	linkedlist *dirlst;
	dirlst = clientgetslashlist();
	ui.lstDirs->setRootIsDecorated(true);
	QTreeWidgetItem *root = new QTreeWidgetItem(ui.lstDirs);
	root->setText(0,tr("/"));
	root->setText(1,tr("/"));
        char dir[300];
	char *result;
	char pathsofar[300];
	QTreeWidgetItem *tmpitem;
	QTreeWidgetItem *curparent;
	while (!((dirlst==NULL) || (dirlst->isEmpty()))) {
	        curparent=root;
	        strcpy(pathsofar,"/");
	        strcpy(dir,dirlst->remove());
	        result=strtok(dir,"/");
	        while (result !=NULL) {
	            strcat(pathsofar,result);
	            QList<QTreeWidgetItem*> items = ui.lstDirs->findItems(tr(pathsofar), Qt::MatchExactly | Qt::MatchRecursive, 0);
		    if (items.empty()) {
			tmpitem=new QTreeWidgetItem(curparent);
                	tmpitem->setText(0,tr(result));
                	tmpitem->setText(0,tr(pathsofar));
                	tmpitem->setText(1,tr(result));
                	tmpitem->setText(1,tr(pathsofar));
		    }
		    else {
			tmpitem = items.first();
		    }
		    items.clear();
		    curparent = tmpitem;
		    result = strtok(NULL,"/");
	            strcat(pathsofar,"/");
		}
	}

}

BrowseFolder::~BrowseFolder()
{

}

QString BrowseFolder::getFolder() {
	return ui.txtLocation->text();
}
void BrowseFolder::on_lstDirs_itemDoubleClicked(QTreeWidgetItem *item,int col) {
    if (item!=NULL) {
            ui.txtLocation->setText(item->text(col));
    }
}
